﻿/*
 * Copyright 2014 Francois Karman
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

using System.ComponentModel.DataAnnotations;

namespace Quartz.WebManager.Model
{
    /// <summary>
    /// Specifies that a data field value is a cron expression.
    /// </summary>
    public class CronExpressionAttribute : ValidationAttribute
    {
        /// <summary>
        /// Gets a value that indicates whether the attribute requires validation context. 
        /// </summary>
        /// <value>
        /// Returns always <c>false</c>.
        /// </value>
        public override bool RequiresValidationContext
        {
            get { return false; }
        }

        /// <summary>
        /// Determines whether the specified cron expression is valid. 
        /// </summary>
        /// <param name="value">The value to validate.</param>
        /// <returns>
        /// <c>true</c> if the cron expression is valid; otherwise <c>false</c>.
        /// </returns>
        /// <remarks>
        /// The cron expression is validated through Quartz.
        /// </remarks>
        public override bool IsValid(object value)
        {
            string text = value as string;
            if (value != null && text == null)
            {
                // The value is not a string
                return false;
            }
            else if (string.IsNullOrWhiteSpace(text))
            {
                // This test is not about required field
                return true;
            }

            return CronExpression.IsValidExpression(text);
        }

        /// <summary>
        /// Applies formatting to an error message, based on the data field where the error occurred. 
        /// </summary>
        /// <param name="name">The name to include in the formatted message.</param>
        /// <returns>An instance of the formatted error message.</returns>
        public override string FormatErrorMessage(string name)
        {
            string format = "The field {0} is not a valid cron expression";
            return string.Format(format, name);
        }
    }
}